package com.sgb.member.ui.fragment;

import android.os.Bundle;
import android.text.TextUtils;
import android.util.SparseArray;
import android.util.SparseIntArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.content.ContextCompat;
import androidx.databinding.DataBindingUtil;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.google.android.material.tabs.TabLayout;
import com.sgb.member.MemberConfig;
import com.sgb.member.PickCateType;
import com.sgb.member.R;
import com.sgb.member.databinding.FragmentMemberTeamBinding;
import com.sgb.member.di.DaggerMemberFragComponent;
import com.sgb.member.di.MemberFragModule;
import com.sgb.member.entity.MemberTeamPersonBean;
import com.sgb.member.ui.activity.MemberBusinessActivity;
import com.sgb.member.ui.adapter.HomeOtherMemberAdapter;
import com.sgb.member.view_model.MemberTeamPersonModel;
import com.swgk.core.base.AppLazyFragment;
import com.swgk.core.base.di.AppComponent;
import com.swgk.core.customview.XCustomTabLayout;
import com.swgk.core.recyclerview.adapter.AdapterOnItemClick;
import com.swgk.core.view.areapopup.AddressEntity;
import com.swgk.core.view.areapopup.GoodsSourceLocationEntity;
import com.swgk.core.view.areapopup.ThreeLevelAreaWindow;
import com.swgk.core.view.selection.CommonPopEntity;
import com.swgk.core.view.selection.CopyUtils;
import com.swgk.core.view.selection.MemberStatusView;
import com.swgk.core.view.selection.XChooseDialog;
import com.swgk.core.view.selection.XChooseEntity;
import com.swgk.core.xrecyclerview.LoadingMoreFooter;
import com.swgk.core.xrecyclerview.XRecyclerView;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

// 会员经营-工程工队-工种报价
public class MemberTeamPersonFragment extends AppLazyFragment implements MemberStatusView.OnChooseListener
        ,XChooseDialog.DialogCallBackImpl {

    @Inject
    public MemberTeamPersonModel sModel;
    private FragmentMemberTeamBinding mBinding;
    private HomeOtherMemberAdapter<MemberTeamPersonBean> mAdapter;
    private int mCurPos; // 主页面TAB下标
    private CommonPopEntity mCurEntity; // 主页面TAB下标
    // 经营地址Popup
    private ThreeLevelAreaWindow mAddressPop;
    private List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>> scrData;

    private String mNo1 = ""; // 1, "工程分类");
    private String mNo4 = ""; // 4, "工种名称");
    private String mNo6 = ""; // 6, "所在地区");
    private String mNo7 = ""; // 7, "所在地");
    private String mNo9 = "";//会员级别
    private SparseIntArray mFilters = new SparseIntArray();
    // 数据集
    private SparseArray<List<CommonPopEntity>> mData = new SparseArray<>();

    public static MemberTeamPersonFragment newInstance(int position, CommonPopEntity entity) {
        MemberTeamPersonFragment fragment = new MemberTeamPersonFragment();
        Bundle bundle = new Bundle();
        bundle.putInt("INDEX", position);
        bundle.putSerializable("ENTITY", entity);
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    protected void setupFragmentComponent(AppComponent appComponent) {
        DaggerMemberFragComponent.builder()
                .appComponent(appComponent)
                .memberFragModule(new MemberFragModule(this))
                .build()
                .inject(this);
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        mBinding = DataBindingUtil.inflate(inflater, R.layout.fragment_member_team, container, false);
        mBinding.setLifecycleOwner(this);
        return mBinding.getRoot();
    }

    @Override
    protected void initView() {
        mCurPos = getArguments().getInt("INDEX", 0);
        mCurEntity = (CommonPopEntity) getArguments().getSerializable("ENTITY");
        mBinding.recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        mBinding.chooseLayout.setVisibility(View.INVISIBLE);
        initPopup();
        initChooseDialog();
        initRecycler();
    }

    @Override
    protected void onLazyLoad() {
        loadData(false);
        loadOtherData();
    }
    public void loadData(boolean isLoadMore) {
        String text = ((MemberBusinessActivity)getActivity()).getSearchText();
        sModel.teamPriceList(isLoadMore, text, mNo1, mNo4, mNo6, mNo7,mNo9);
    }

    private void loadOtherData() {
        if (isListEmpty(PickCateType.TYPE_1)) {
            sModel.getCategoryTrees(PickCateType.TYPE_1, false);
        }
        if (isListEmpty(PickCateType.TYPE_4)) {
            sModel.getWorkType(PickCateType.TYPE_4, false);
        }
        if (scrData == null || scrData.size() == 0) {
            sModel.getAddressModel(PickCateType.TYPE_6);  // 经营地址
        }
        if (isListEmpty(PickCateType.TYPE_9)) {
            sModel.getMemberLevelData(PickCateType.TYPE_9); // 会员级别
        }
    }

    private SparseArray<String> mNameArray;
    private XChooseDialog mChooseDialog;
    private void initChooseDialog() {
        mNameArray = new SparseArray<>();
        mNameArray.put(PickCateType.TYPE_9, "会员级别");
        mChooseDialog = new XChooseDialog(getContext(), mNameArray);
        mChooseDialog.setCallBack(this);
        for (int i = 0; i < mNameArray.size(); i++) {
            int key = mNameArray.keyAt(i);
            addMainEntity(key, new ArrayList<>());
        }
    }


    private boolean isListEmpty(int catType) {
        return mData.get(catType) == null || mData.get(catType).size() == 0;
    }

    public void setAddressData(List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>> data) {
        if (data != null && data.size() > 0) {
            scrData = data;
            if (TextUtils.isEmpty(mNo6)) {
                mAddressPop.setData(data, true);
            } else {
                mAddressPop.setDataAndPosition(data, mNo6, mNo7, "", true, true);
            }
        } else {
            sModel.getAddressModel(PickCateType.TYPE_6);
        }
    }

    private void showChildTab(List<CommonPopEntity> data) {
        if (data == null && data.size() == 0) {
            mBinding.childTab.setVisibility(View.GONE);
            return;
        }
        mBinding.childTab.setVisibility(View.VISIBLE);
        mBinding.childTab.removeAllTabs();
        for (int i = 0; i < data.size(); i++) {
            mBinding.childTab.addTab(mBinding.childTab.newTab().setText(data.get(i).getTypeName()));
        }
        mBinding.childTab.setNormalColor(R.color.color_title_small);
        mBinding.childTab.addOnTabSelectedListener(data, new XCustomTabLayout.SimpleSelectedListener(){

            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                int pos = tab.getPosition();
                List<CommonPopEntity> list = mData.get(PickCateType.TYPE_1);
                mNo1 = list.get(pos).getNo();
                loadData(false);
            }
        });
        mBinding.childTab.scrollTo(0, 0);
    }

    /**
     * -------------------------------------initRecycler------------------------------------------
     */
    private void initRecycler() {
        TextView textView = mBinding.emptyView.findViewById(R.id.no_data_count);
        textView.setVisibility(View.VISIBLE);
        mBinding.recyclerView.setPullRefreshEnabled(true);
        mBinding.recyclerView.setLoadingMoreEnabled(true);
        LoadingMoreFooter footer = (LoadingMoreFooter) mBinding.recyclerView.getFootView();
        footer.setNoMoreHint("已经到底啦~");
        mBinding.recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        mBinding.recyclerView.setLoadingListener(new XRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {
                loadData(false);
            }

            @Override
            public void onLoadMore() {
                loadData(true);
            }
        });
        initRecyclerAdapter(0);
    }

    private void initRecyclerAdapter(int index) {
        DividerItemDecoration divider3 = new DividerItemDecoration(getActivity(), DividerItemDecoration.VERTICAL);
        divider3.setDrawable(ContextCompat.getDrawable(getActivity(), R.drawable.shape_list_divide2));
        mBinding.recyclerView.addItemDecoration(divider3);
        mAdapter = new HomeOtherMemberAdapter<MemberTeamPersonBean>(getActivity(), R.layout.item_other_team_person, null);
        mAdapter.setOnItemClick(new AdapterOnItemClick<MemberTeamPersonBean>() {
            @Override
            public void onItemClick(MemberTeamPersonBean teamPriceItemEntity, int position) {
                MemberConfig.getInstance().startTeamOfferDetail(getActivity(), teamPriceItemEntity.getNo());
            }
        });
        if (mAdapter != null) {
            mBinding.recyclerView.setAdapter(mAdapter);
        }
    }

    public void closeRecyclerRefreshing() {
        mBinding.recyclerView.refreshComplete();
        mBinding.recyclerView.loadMoreComplete();
    }

    public void showEmpty() {
        mBinding.recyclerView.setVisibility(View.GONE);
        mBinding.emptyView.setVisibility(View.VISIBLE);
    }

    public void refreshRecycler(List<MemberTeamPersonBean> list, boolean isLoadMore, boolean noMoreData) {
        mBinding.recyclerView.setVisibility(View.VISIBLE);
        mBinding.recyclerView.setNoMore(noMoreData);
        closeRecyclerRefreshing();
        if (isLoadMore) {
            if (list != null && list.size() > 0) {
                mAdapter.addDatas(list);
            }
        } else {
            if (list != null && list.size() > 0) {
                mBinding.emptyView.setVisibility(View.GONE);
                mAdapter.setDatas(list);
            } else {
                mAdapter.clearDatas();
                mBinding.emptyView.setVisibility(View.VISIBLE);
            }
        }
    }

    /**
     * ------------------------------- Popup ---------------------------------------------
     */
    private void initPopup() {
        mBinding.popup1.setVisibility(View.GONE);
        mBinding.popup2.setVisibility(View.GONE);
        mBinding.popup21.setVisibility(View.VISIBLE);
//        mBinding.popup1.initPopup(mBinding.grayLayout, mBinding.popLine, this);
        mBinding.popupMemberLever.initPopup(mBinding.grayLayout, mBinding.popLine, this);
        mBinding.popup21.initPopup(mBinding.grayLayout, mBinding.popLine, this);
        initAddressPopup();
    }

    private void initAddressPopup() {
        mBinding.popup3.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (scrData == null) {
                    sModel.getAddressModel(PickCateType.TYPE_6);
                    return;
                }
                mBinding.popLine.setVisibility(View.VISIBLE);
                if (!TextUtils.isEmpty(mNo6) || !TextUtils.isEmpty(mNo7)) {
                    mBinding.popup3.updateChooseTextStatus(-2, null);
                } else {
                    mBinding.popup3.updateChooseTextStatus(-1, mBinding.popup3.getKeyName());
                }
                mAddressPop.showPopwindow0(mBinding.popLine);
            }
        });
        mAddressPop = new ThreeLevelAreaWindow(getActivity());
        mAddressPop.setMemberHeight();
        mAddressPop.setCitySingle();
        mAddressPop.setProvinceSingle();
        mAddressPop.setShowSimpleName(true);
        mAddressPop.setOnlyShowProAndCity(true);
        mAddressPop.setAllSingleSelect(true);
        mAddressPop.setThreeListIsGone(true);
        mAddressPop.setOnResultClick(new ThreeLevelAreaWindow.OnResultClickProxy() {
            @Override
            protected void result(GoodsSourceLocationEntity entity) {
                mNo6 = "";
                mNo7 = "";
                mBinding.popup3.updateChooseTextStatus(0, mBinding.popup3.getKeyName());
                if (!TextUtils.isEmpty(entity.getProvinceNo())) {
                    mNo6 = entity.getProvinceNo();
                    mBinding.popup3.updateChooseTextStatus(1, entity.getProvinceName());
                    if (!TextUtils.isEmpty(entity.getCityNo())) {
                        mNo7 = entity.getCityNo();
                        mBinding.popup3.updateChooseTextStatus(1, entity.getCityName());
                    }
                }
                //刷新数据
                loadData(false);
            }
        });
        mAddressPop.setOnDismissListener(() -> {
            mBinding.popLine.setVisibility(View.GONE);
            if (!TextUtils.isEmpty(mNo6) || !TextUtils.isEmpty(mNo7)) {
                mBinding.popup3.updateChooseTextStatus(1, null);
            } else {
                mBinding.popup3.updateChooseTextStatus(0, mBinding.popup3.getKeyName());
            }
        });
    }

    @Override
    public void onLoadChooseData(String mKeyName) {
        switch (mKeyName) {
            case "工程分类":
                sModel.getCategoryTrees(PickCateType.TYPE_1, false);
                break;
            case "工种名称":
                sModel.getWorkType(PickCateType.TYPE_4, false);
                break;
        }
    }

    @Override
    public void onChooseResult(String mKeyName, CommonPopEntity entity, Object... objects) {
        int position = (int) objects[0];
        String no = position == 0 ? "" : entity.getNo();
        String id = position == 0 ? "" : entity.getId();
        String name = position == 0 ? "" : entity.getTypeName();
        switch (mKeyName) {
            case "工程分类":
                if (!TextUtils.equals(no, mNo1)) {
                    mNo1 = no;
                    loadData(false);
                }
                break;
            case "工种名称":
                if (!TextUtils.equals(no, mNo4)) {
                    mNo4 = no;
                    loadData(false);
                }
                break;
            case "会员级别":
                if (!TextUtils.equals(no, mNo9)) {
                    mNo9 = entity.getId();
                    mFilters.put(PickCateType.TYPE_9, position);
                    loadData(false);
                }
                break;
        }
    }

    public void setChooseItemData(int type, List<CommonPopEntity> data) {
        if (data == null || data.size() == 0) return;
        addMainEntity(type, data);
        switch (type) {
            case PickCateType.TYPE_1:
                showChildTab(data);
                break;
            case PickCateType.TYPE_4:
                mBinding.popup21.setData(data, mNo4);
                break;
            case PickCateType.TYPE_9:
                mBinding.popupMemberLever.setData(data, mNo9);
                break;
        }
    }


    public void addMainEntity(int index, List<CommonPopEntity> list) {
        if (mData.get(index) != null) {
            if (list == null || list.size() == 0) {
                mData.get(index).clear();
            } else {
                mData.put(index, list);
            }
        } else {
            mData.put(index, list);
        }
        mFilters.put(index, 0);
    }

    @Override
    public void loadChildData(XChooseEntity entity, int pos) {

    }
    private SparseArray<XChooseEntity> mData_x = new SparseArray<>();
    @Override
    public void result(SparseArray<XChooseEntity> data, SparseIntArray map) {
        mData_x = CopyUtils.deepPopEntityCopy(data);
        mFilters = map.clone();
        for (int i = 0; i < mData_x.size(); i++) {
            XChooseEntity entity = mData_x.get(mData_x.keyAt(i));
            int key = entity.getSort();
            int value = mFilters.get(key);
            switch (key) {
                case PickCateType.TYPE_9:
                    mNo9 = entity.getItemNo(value);
                    mBinding.popupMemberLever.refreshChoose(mNo9, entity.getItemName(value), value);
                    break;
                default:
                    break;
            }
        }
        loadData(false);
    }

    @Override
    public void reset() {
        mFilters.clear();
        mChooseDialog.initData(mData_x, mFilters);
        mChooseDialog.showDialog();
    }

    @Override
    public void onCancel() {
        mChooseDialog.initData(mData_x, mFilters);
    }
}
